package com.example.accessingdatajpa.service.impl;

import com.example.accessingdatajpa.exception.ResourceNotFoundException;
import com.example.accessingdatajpa.pojo.Customer;
import com.example.accessingdatajpa.pojo.Role;
import com.example.accessingdatajpa.repository.CustomerRepository;
import com.example.accessingdatajpa.repository.RoleRepository;
import com.example.accessingdatajpa.response.RestResponse;
import com.example.accessingdatajpa.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.List;

@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private RoleRepository roleRepository;

    private final PasswordEncoder encoder = new BCryptPasswordEncoder();//定义密码的加密程序

    //查询全部用户
    @Override
    @Transactional
    public RestResponse<List<Customer>> queryAllCustomers(){
        RestResponse<List<Customer>> response = new RestResponse<>();
        try {
            List<Customer> data = customerRepository.findAll();
            response.setStatus(200);
            response.setMessage("查询成功");
            response.setData(data);
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    //新增用户
    @Override
    @Transactional
    public RestResponse<String> addOneCustomer(Customer customer, HttpServletRequest request){
        RestResponse<String> response = new RestResponse<>();
        try {
            //判断数据表中是否存在重复用户名
            if(customerRepository.findByUserName(customer.getUserName())==null){//表中不存在该用户名
                HttpSession session = request.getSession();//得到session，目前没什么用
                Role role = new Role();//新建角色
                role.setRoleId(1L);//默认为普通用户
                customer.setRole(role);//保存用户角色
                customer.setUserPassword(encoder.encode(customer.getUserPassword()));//对用户密码进行加密并储存
                session.setAttribute(customer.getUserName(), customer);//保存session，目前没什么用
                customerRepository.save(customer);//保存用户
                response.setStatus(200);
                response.setMessage("ok");
                response.setData("保存成功");
            }else {//存在重复用户名
                response.setStatus(500);
                response.setMessage("failed");
                response.setData("用户名已存在");
            }
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
            response.setData("保存失败");
        }
        return response;
    }

    //用户权限升级
    @Override
    @Transactional
    public RestResponse<Role> updateCustomerAuthority(Long customerId, Long roleId){
        RestResponse<Role> response = new RestResponse<>();
        try {
            //在用户数据表中寻找用户位置，判断是否存在，不存在会报错
            Customer customer = customerRepository.findById(customerId)
                    .orElseThrow(() -> new ResourceNotFoundException("customer","customerId",customerId));
            Role role = new Role();//新建角色
            role.setRoleId(roleId);//更新用户的权限等级
            role.setRoleName(roleRepository.findById(roleId).get().getRoleName());//从角色表中提取该用户权限等级对应的名称，并存入该用户的角色中
            customer.setRole(role);//覆盖之前的用户角色，其他部分保持不变
            response.setStatus(200);
            response.setMessage("您的权限升级为"+role.getRoleName());
            response.setData(role);
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    //进行登录认证
    @Override
    @Transactional
    public RestResponse<Long> authenticateCustomer(String userName,String userPassword){
        RestResponse<Long> response = new RestResponse<>();
        try {
            //按照用户名查找用户，判断是否存在
            if (customerRepository.findByUserName(userName)==null){//该用户不存在
                response.setStatus(400);
                response.setMessage("用户名不存在");
            }else {
                Customer customer = customerRepository.findByUserName(userName);//若存在，定位至该用户位置
                if(encoder.matches(userPassword, customer.getUserPassword())){//判断输入的密码与数据库中的密码是否匹配
                    response.setStatus(200);
                    response.setMessage("登录成功");
                    response.setData(customer.getCustomerId());//登录成功则返回用户id
                }else {
                    response.setStatus(500);
                    response.setMessage("密码错误，请重新输入");
                }
            }
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    //删除用户
    @Override
    @Transactional
    public RestResponse<String> deleteOneCustomer(Long customerId){
        RestResponse<String> response = new RestResponse<>();
        try {
            //根据用户id寻找数据表中是否存在该用户
            Customer customer = customerRepository.findById(customerId)
                    .orElseThrow(() -> new ResourceNotFoundException("customer","customerId",customerId));
            customerRepository.delete(customer);//若存在，直接删除
            response.setStatus(200);
            response.setMessage("ok");
            response.setData("删除成功");
        }catch (RuntimeException e){
            response.setStatus(500);
            response.setMessage(e.getMessage());
            response.setData("删除失败");
        }
        return response;
    }

}
